package ltd.jdsoft.cute.spring.web.util;

import javax.servlet.http.HttpServletRequest;

/**
 * 网络工具类
 * 
 * @author zhengzhq
 *
 */
public class NetUtils {

  /**
   * 获取远程服务器的IP
   * 
   * @param request
   * @return
   */
  public static String getRemoteIp(HttpServletRequest request) {
    // 如果是代理服务器，会有该头部信息，代表真实主机
    String ip = request.getHeader("X-Forwarded-For");

    // 直接获取真实主机IP。有代理服务器的情况下该字段返回的是代理服务器的IP
    if (isInValidIP(ip)) {
      ip = request.getHeader("X-Real-IP");
    }
    if (isInValidIP(ip)) {
      ip = request.getRemoteAddr();
    }
    return ip;
  }

  /**
   * 判断IP是否有效
   * 
   * @param ip
   * @return
   */
  private static boolean isInValidIP(String ip) {
    return ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip);
  }
}
